package com.codeczx.myretrofitdemo.retrofit;


import android.util.Log;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.Executor;

/**
 * Created by codeczx on 2018/3/7.
 */

class ExecutorCallAdapterFactory extends CallAdapter.Factory {

    private static final String TAG = "ExecutorCallAdapterFact";
    final Executor callbackExecutor;

    ExecutorCallAdapterFactory(Executor callbackExecutor) {
        this.callbackExecutor = callbackExecutor;
    }

    @Override
    CallAdapter<?, ?> get(final Type returnType, Annotation[] annotations) {

        CallAdapter<Object, Call<?>> callAdapter = new CallAdapter<Object, Call<?>>() {
            @Override
            public Type returnType() {
                return returnType;
            }

            @Override
            public Call<?> adapt(Call<Object> call) {
                return new ExecutorCallbackCall(callbackExecutor, call);
            }
        };
        return callAdapter;
    }


    static final class ExecutorCallbackCall<T> implements Call<T> {

        final Executor callbackExecutor;
        final Call<T> delegate;

        public ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
            this.callbackExecutor = callbackExecutor;
            this.delegate = delegate;
        }

        @Override
        public Response<T> execute() {
            return delegate.execute();
        }

    }
}
